from models import MetricSite, MetricSet
from utils import get_all_times
from datetime import datetime, timedelta
from django.conf import settings

def process_form_inputs(data):
    sitename = data.get('site', None)
    setname = data.get('set', None)

    is_configured = False # Change to True only when everything loaded OK


    metsites = MetricSite.objects.all()
    all_metric_sitenames = [ms.name for ms in metsites]        
    all_metric_setnames = []

    metric_site = None
    metric_set = None
    
    if len(all_metric_sitenames) > 0:
        if sitename and sitename in all_metric_sitenames:
            metric_site = metsites.filter(name=sitename)[0]
        else:
            metric_site = metsites[0]
        
        metsets = MetricSet.objects.filter(metricsite=metric_site)
        all_metric_setnames = [ms.name for ms in metsets]
        
        if len(all_metric_setnames) > 0:
            if setname and setname in all_metric_setnames:
                try:
                    metric_set = metsets.filter(name=setname)[0]
                except:
                    metric_set = metsets[0]
            else:
                metric_set = metsets[0]
            is_configured = True
    
    all_metric_sitenames_count = len(all_metric_sitenames)
    all_metric_setnames_count = len(all_metric_setnames)
    
    use_table = data.has_key('table') and data['table'] != '0'

    # Get an ordered list of all dates.
    all_times = get_all_times(metric_set)
    
    # Another list with just dates and remove duplicates
    date_choices = list(set([dt.strftime("%Y-%m-%d") for dt in all_times]))

    if all_times:
        has_data = True
            
        # Choose a default start/end date if none specified already
        if data.has_key('enddate'):
            end_date_str = data['enddate']
        else:
            end_date_str = 'All'
            
        if data.has_key('startdate'):
            start_date_str = data['startdate']
        else:
            # Use default_history_mins
            dhm = metric_set.default_history_mins
            if dhm <= 0:
                dhm = getattr(settings, 'DEFAULT_HISTORY_MINS', 10*24*metric_set.collection_mins) # 10 days?
            suggested_start_date = all_times[-1] - timedelta(minutes=dhm)
            if all_times[0] > suggested_start_date:
                start_date_str = 'All'
            else:
                suggested_start_date = [dt for dt in all_times if dt >= suggested_start_date][0]
                start_date_str = suggested_start_date.strftime("%Y-%m-%d")
        
        #if start_date_str != 'All':
        try:
            start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
        except ValueError:
            start_date = all_times[0]
            start_date_str = 'All'
    
        #if end_date_str != 'All':
        try:
            end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
        except ValueError:
            end_date = all_times[-1]
            end_date_str = 'All'
        
        # To make sure we are inclusive of the very last date when choosing datetimes
        end_date += timedelta(days=1)
            
        if start_date_str != 'All' and end_date_str != 'All' and start_date > end_date:
            start_date_str, end_date_str = end_date_str, start_date_str
            start_date, end_date = end_date, start_date
    else:
        has_data = False
        start_date_str = 'All'
        end_date_str = 'All'
                
    # Finally restrict all_times to just those in the range
    new_all_times = [t for t in all_times if t >= start_date and t < end_date]
    if has_data and not new_all_times:
        new_all_times = all_times
        has_data = True
        start_date_str = 'All'
        end_date_str = 'All'
        
    all_times = new_all_times
    date_choices_with_all = ['All'] + date_choices
    
    return locals()
